<template>
  <el-dialog
    v-model="visible"
    title="规则详情"
    width="800px"
    :close-on-click-modal="false"
  >
    <div class="detail-content">
      <!-- 基本信息 -->
      <div class="detail-section">
        <h3 class="section-heading">📌 规则基本信息</h3>
        <el-descriptions :column="1" border>
          <el-descriptions-item label="规则名称">{{
            displayRule.name
          }}</el-descriptions-item>
          <el-descriptions-item label="规则类型">{{
            displayRule.type
          }}</el-descriptions-item>
          <el-descriptions-item label="规则描述">{{
            displayRule.description
          }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag
              :type="displayRule.status === '启用中' ? 'success' : 'info'"
            >
              {{ displayRule.status }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建人">{{
            displayRule.creator
          }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{
            displayRule.createTime
          }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{
            displayRule.updateTime || "未更新"
          }}</el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 匹配条件 -->
      <div class="detail-section">
        <h3 class="section-heading">🎯 匹配条件</h3>
        <el-descriptions :column="1" border>
          <el-descriptions-item label="条件内容">{{
            displayRule.condition
          }}</el-descriptions-item>
          <el-descriptions-item label="条件类型">
            <template v-if="displayRule.type === 'IP段'"> IP段 </template>
            <template v-else>{{ displayRule.type }}</template>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 适用场景 -->
      <div class="detail-section">
        <h3 class="section-heading">🔍 适用场景</h3>
        <div class="scene-tags">
          <el-tag
            v-for="scene in applicableScenes"
            :key="scene"
            type="info"
            class="scene-tag"
          >
            {{ scene }}
          </el-tag>
        </div>
      </div>

      <!-- 生效时间 -->
      <div class="detail-section">
        <h3 class="section-heading">⏱️ 生效时间</h3>
        <el-descriptions :column="1" border>
          <el-descriptions-item label="开始时间">{{
            displayRule.hasExpireTime ? displayRule.startTime : "无限制(永久)"
          }}</el-descriptions-item>
          <el-descriptions-item label="结束时间">{{
            displayRule.hasExpireTime ? displayRule.endTime : "无限制(永久)"
          }}</el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 命中统计 -->
      <div class="detail-section">
        <h3 class="section-heading">📊 命中统计</h3>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="总命中次数">{{
            displayRule.totalHits
          }}</el-descriptions-item>
          <el-descriptions-item label="最后命中">{{
            displayRule.lastHit
          }}</el-descriptions-item>
          <el-descriptions-item label="日均命中">{{
            displayRule.dailyHits
          }}</el-descriptions-item>
          <el-descriptions-item label="本周命中">{{
            displayRule.weeklyHits
          }}</el-descriptions-item>
          <el-descriptions-item label="本月命中">{{
            displayRule.monthlyHits
          }}</el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 最近命中记录 -->
      <div class="detail-section">
        <h3 class="section-heading">📝 最近命中记录 (最近10条)</h3>
        <el-table
          :data="displayRule.hitRecords"
          border
          size="small"
          class="hit-table"
          v-if="displayRule.hitRecords && displayRule.hitRecords.length > 0"
        >
          <el-table-column prop="time" label="命中时间" min-width="140" />
          <el-table-column prop="ip" label="资产IP" min-width="120" />
          <el-table-column prop="scene" label="场景类型" min-width="120" />
        </el-table>
        <div v-else class="no-data">暂无命中记录</div>
        <el-button
          type="text"
          size="small"
          class="view-all-btn"
          v-if="displayRule.hitRecords && displayRule.hitRecords.length > 0"
        >
          查看全部命中记录
        </el-button>
      </div>
    </div>

    <template #footer>
      <el-button @click="handleCancel">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, defineProps, defineEmits, computed } from "vue";

// 定义props
const props = defineProps({
  modelValue: { type: Boolean, default: false },
  rule: {
    type: Object,
    default: () => ({}),
  },
});

// 定义emits
const emit = defineEmits<{
  (e: "update:modelValue", value: boolean): void;
  (e: "edit", rule: any): void;
  (e: "change-status", rule: any, status: string): void;
  (e: "delete", rule: any): void;
}>();

// visible computed 属性
const visible = computed({
  get: () => props.modelValue,
  set: (value: boolean) => emit("update:modelValue", value),
});

// 规则类型映射
const ruleTypeMap: Record<string, string> = {
  ip: "IP地址",
  ip_range: "IP段",
  port: "端口",
  ip_port: "IP+端口",
  scene: "场景",
  vuln_type: "漏洞",
};

// 格式化匹配条件
const formatMatchCondition = (condition: any): string => {
  if (!condition) return "-";

  if (typeof condition === "string") {
    return condition;
  }

  if (typeof condition === "object") {
    const { field, operator, value } = condition;
    const operatorMap: Record<string, string> = {
      equals: "等于",
      not_equals: "不等于",
      contains: "包含",
      not_contains: "不包含",
      starts_with: "开头为",
      ends_with: "结尾为",
      in_range: "范围内",
      not_in_range: "范围外",
      greater_than: "大于",
      less_than: "小于",
      greater_equal: "大于等于",
      less_equal: "小于等于",
    };

    const operatorText = operatorMap[operator] || operator;
    const fieldText = field || "";
    const valueText = value || "";

    if (operator === "in_range" || operator === "not_in_range") {
      if (Array.isArray(value)) {
        return `${fieldText} ${operatorText} [${value.join(", ")}]`;
      }
      return `${fieldText} ${operatorText} ${valueText}`;
    }

    return `${fieldText} ${operatorText} ${valueText}`;
  }

  return "-";
};

// 格式化时间
const formatTime = (time: string | null | undefined): string => {
  if (!time) return "-";
  return time.replace("T", " ").substring(0, 19);
};

// 转换适用场景为中文
const applicableScenes = computed(() => {
  const sceneMap: Record<string, string> = {
    unreported_asset: "未报备资产告警",
    high_risk_asset: "高危资产告警",
    vuln_scan: "漏洞扫描告警",
    intel_hit: "威胁情报告警",
    reviewed: "漏洞复核告警",
    all: "全部场景",
  };

  if (!props.rule.applicable_dimensions) {
    return ["全部场景"];
  }

  // 处理数组或字符串两种情况
  let dimensions: string[] = [];
  if (Array.isArray(props.rule.applicable_dimensions)) {
    dimensions = props.rule.applicable_dimensions;
  } else if (typeof props.rule.applicable_dimensions === "string") {
    dimensions = props.rule.applicable_dimensions.split(",");
  }

  if (dimensions.length === 0) {
    return ["全部场景"];
  }

  return dimensions
    .map((dim: string) => sceneMap[dim.trim()] || dim.trim())
    .filter(Boolean);
});

// 计算显示的规则数据
const displayRule = computed(() => {
  const rule = props.rule;
  return {
    name: rule.rule_name || "-",
    type:
      rule.rule_type_name ||
      ruleTypeMap[rule.rule_type] ||
      rule.rule_type ||
      "-",
    description: rule.rule_description || rule.description || "无",
    status: rule.is_enabled ? "启用中" : "已禁用",
    creator: rule.created_by || "-",
    createTime: formatTime(rule.created_at),
    updateTime: formatTime(rule.updated_at),
    condition: formatMatchCondition(rule.match_condition),
    hasExpireTime: !!(rule.effective_start || rule.effective_end),
    startTime: formatTime(rule.effective_start),
    endTime: formatTime(rule.effective_end),
    totalHits: rule.match_count || rule.totalHits || 0,
    lastHit: formatTime(rule.last_matched_at) || rule.lastHit || "无",
    dailyHits:
      rule.statistics?.daily_average !== undefined
        ? `${rule.statistics.daily_average.toFixed(1)}次/天`
        : rule.dailyHits || "0次/天",
    weeklyHits: rule.statistics?.week_count || rule.weeklyHits || 0,
    monthlyHits: rule.statistics?.month_count || rule.monthlyHits || 0,
    hitRecords: rule.recent_matches || rule.hitRecords || [],
  };
});

// 编辑
const handleEdit = () => {
  emit("edit", props.rule);
};

// 切换状态
const handleChangeStatus = () => {
  const newStatus = displayRule.value.status === "启用中" ? "已禁用" : "启用中";
  emit("change-status", props.rule, newStatus);
};

// 删除
const handleDelete = () => {
  emit("delete", props.rule);
};

// 取消
const handleCancel = () => {
  emit("update:modelValue", false);
};
</script>

<style scoped lang="scss">
.detail-content {
  max-height: 600px;
  overflow-y: auto;
  padding-right: 10px;
}

.detail-section {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }
}

.section-heading {
  font-size: 15px;
  font-weight: 500;
  margin: 0 0 10px 0;
  color: #555;
  display: flex;
  align-items: center;
  gap: 8px;
}

.scene-tags {
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 4px;
  min-height: 40px;

  .scene-tag {
    margin-right: 10px;
    margin-bottom: 5px;
  }
}

.hit-table {
  margin-bottom: 10px;
}

.view-all-btn {
  color: #1890ff;
  padding: 0;
}

.no-data {
  text-align: center;
  padding: 20px;
  color: #999;
  font-size: 14px;
}
</style>
